#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time          : 2025/4/21 14:51
# File          : add_watermark
# @Author       : MingTai
# @Department   : csc_qa

from PIL import Image, ImageDraw, ImageFont


def add_watermark(input_image_path, output_image_path, watermark_text, position=(10, 10), font_size=30, opacity=200):
    try:
        # 打开原始图片
        original_image = Image.open(input_image_path).convert("RGBA")
        print(f"成功打开图片: {input_image_path}，尺寸: {original_image.size}")

        # 创建一个与原始图片相同大小的透明图层
        watermark = Image.new('RGBA', original_image.size, (0, 0, 0, 0))

        # 在透明图层上绘制水印文字
        draw = ImageDraw.Draw(watermark)
        # 使用系统默认字体
        font = ImageFont.load_default()
        # 使用 textbbox 计算文本的边界框
        bbox = draw.textbbox((0, 0), watermark_text, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]
        print(f"水印文字尺寸: 宽度 {text_width}，高度 {text_height}")

        # 更改水印颜色为红色，便于观察
        draw.text(position, watermark_text, fill=(255, 0, 0, opacity), font=font)

        # 合并原始图片和水印图层
        combined = Image.alpha_composite(original_image, watermark)

        # 保存添加水印后的图片
        combined.save(output_image_path, "PNG")
        print(f"水印已添加到图片，保存至 {output_image_path}")
    except FileNotFoundError:
        print(f"错误: 文件 {input_image_path} 未找到。")
    except Exception as e:
        print(f"错误: 发生了未知错误 {e}")


if __name__ == "__main__":
    input_image = "/Users/tianmingtai/Downloads/WechatIMG32.jpg"  # 替换为你的输入图片路径
    output_image = "output.png"  # 替换为你的输出图片路径
    watermark_text = "Your Watermark"  # 替换为你要添加的水印文字
    add_watermark(input_image, output_image, watermark_text)